package epay18

import (
	"context"
	"navi-mumbai/app/rpc/pay/pb"
	pb2 "navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/key/walletkey"
	"strconv"

	"navi-mumbai/app/api/pay/internal/svc"
	"navi-mumbai/app/api/pay/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AutoDepositNotifyEpay18Logic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAutoDepositNotifyEpay18Logic(ctx context.Context, svcCtx *svc.ServiceContext) *AutoDepositNotifyEpay18Logic {
	return &AutoDepositNotifyEpay18Logic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AutoDepositNotifyEpay18Logic) AutoDepositNotifyEpay18(reqContent *types.DepositNotifyEpay18ReqContent) (resp *types.WithdrawNotifyEpay18Resp, err error) {
	l.Logger.Infof("AutoDepositNotifyEpay18Logic svcCtx.Pay.AutoDepositNotifyEpay18 reqContent: %+v", reqContent)
	var fn int64
	fn, err = strconv.ParseInt(reqContent.MerchantTradeNo, 10, 64)
	if err != nil {
		l.Logger.Errorf("DepositNotifyEpay18Logic strconv.ParseInt(reqContent.MerchantTradeNo:%s) error(%v)", reqContent.MerchantTradeNo, err)
		return
	}
	// 更新支付网关流水状态
	in := pb.UpdateEpay18DepositResultReq{
		PayGwFlowNo:  fn,
		TradeStatus:  reqContent.TradeStatus,
		Amount:       reqContent.Amount,
		ExFlowNo:     reqContent.TradeNo,
		NotifyTime:   reqContent.NotifyTime,
		PayChannelId: walletkey.PayChannelIdEpay18_UPI,
	}
	var rsp *pb.UpdateEpay18DepositResultResp
	rsp, err = l.svcCtx.PaySysRpc.UpdateEpay18DepositResult(l.ctx, &in)
	if err != nil {
		l.Logger.Errorf("DepositNotifyEpay18Logic svcCtx.Pay.UpdateDepositResult error(%v)", err)
		return
	}

	// 更新用户钱包余额
	var in2 pb2.UpdateDepositResultReq
	in2 = pb2.UpdateDepositResultReq{
		Uid:            rsp.Uid,
		FlowNo:         rsp.WalletFlowNo,
		State:          GetPayStateByEpayTradeStatus(reqContent.TradeStatus),
		ExternalFlowNo: reqContent.TradeNo,
		Amount:         reqContent.Amount,
		ErrMsg:         "",
		PayGwFlowNo:    fn,
	}

	_, err = l.svcCtx.WalletSysRpc.UpdateDepositResult(l.ctx, &in2)
	if err != nil {
		l.Logger.Errorf("DepositNotifyEpay18Logic svcCtx.WalletSysRpc.UpdateDepositResult error(%v)", err)
		return
	}
	return
}
